package com.dfxy.blog.dao;

import com.dfxy.blog.entity.User;
import com.mysql.cj.util.StringUtils;

import javax.xml.crypto.Data;
import java.sql.*;

public class UserDao {
    public User logOn(Connection con, User user) throws SQLException {
        if (con == null || user == null
                || StringUtils.isEmptyOrWhitespaceOnly(user.getUserName())
                || StringUtils.isEmptyOrWhitespaceOnly(user.getPassword())
        ) {
            return null;
        }

        // 判断用户是否已存在
        String sql = "select * from user where username = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, user.getUserName());

        ResultSet rs = pstat.executeQuery();
        if (rs.next()) {
            return null;
        }

        // 用户名和密码写入表
        // insert into user values (123,456)
        sql = "insert into user values (?,?,null)";
        pstat = con.prepareStatement(sql);
        pstat.setString(1, user.getUserName());
        pstat.setString(2, user.getPassword());

        int update_result = pstat.executeUpdate();
        if (update_result == 0) {
            return null;
        }

        return user;
    }

    public User logIn(Connection con, User user) throws SQLException {
        if (con == null || user == null
                || StringUtils.isEmptyOrWhitespaceOnly(user.getUserName())
                || StringUtils.isEmptyOrWhitespaceOnly(user.getPassword())
        ) {
            return null;
        }

        // 判断用户+密码是否已存在
        String sql = "select * from user where username = ? and password = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, user.getUserName());
        pstat.setString(2, user.getPassword());

        ResultSet rs = pstat.executeQuery();
        if (rs.next()) {

            String lastLogInTime = rs.getString("last_login_time");
            System.out.println(lastLogInTime);
            user.setLastLogInTime(lastLogInTime);

            sql = "update user set last_login_time = ? where username = ? and password = ?";
            pstat = con.prepareStatement(sql);

            Date logInTime = new Date(System.currentTimeMillis());
            pstat.setString(1, BlogDao.dateTimeFormat(logInTime));
            pstat.setString(2, user.getUserName());
            pstat.setString(3, user.getPassword());

            int logInResult = pstat.executeUpdate();
            if (logInResult <= 0) {
                return null;
            }

            return user;
        }

        return null;
    }
}
